<?php

	fta_registerModules(
		array(
			"FTAORM/FTAORM",
			"FTAORM/_FTAORMCMSContent",

			"FTAORM/FTAORMCMSContentMetadata",
			"FTAORM/FTAORMCMSBinaryData",
			"FTAORM/FTAORMCMSMultipleKeyValuePair",
			"FTAORM/FTAORMCMSManyToManyWrapper",
	
		)
	);

	

	
	class FTAORMCMSContent extends _FTAORMCMSContent  {
		// add functionality here for access the cms content table.. 
		// this class will not do all the magical defaulting that happens with the standard mechanism
	
	
		function __construct(Zend_Db_Adapter_Abstract $zdb){
			parent::__construct($zdb);
			
			// here we need to remove the fieldes that are not being mapped/remapped
			// but ensure that we have the important fields still in place
			//array_values($this->fieldMap);

			$this->tableFields = array_intersect($this->tableFields, array_merge(array_values($this->fieldMap), array($this->primaryKey, 'formid','documenttypecode','cmscontentmetadata')) );
			$this->fieldMap = array_merge( array($this->primaryKey => $this->primaryKey, 'formid'=>'formid','documenttypecode'=>'documenttypecode'), $this->fieldMap);
			
			$this->setDefaults();
		}
	
		function setDefaults(){
			parent::setDefaults();
		}

		
		function getTablePrefix() {
			return '';	
		}
		
		function getTableBaseName(){
			return $this->tableName;
		}
				
		public function getCmscontentmetadata(){
			$cmsmd =  $this->getOneToOneObjectWithNameAndClass('cmscontentmetadata','FTAORMCMSContentMetadata');
			if (is_null($cmsmd)){
				$cmsmd = new FTAORMCMSContentMetadata($this->zdb);
				$this->_cmscontentmetadata = $cmsmd;
			}
			return $cmsmd;
		}
		
		
		function isValid(){
			return parent::isValid();
		}

		function getBinarydata(){
			if (isset($this->_bin )) {
				return $this->_bin;
			} else if (!isset($this->_bin) && !is_null($this->getPrimaryKey())){
				//we have no tags.. and possibly a primary .. so we should try and fault em
				// the get tags retuns an empty array.. if nothing is foudn..
				$this->_bin = FTAORMCMSBinaryData::getAllBinaryDataForDocumentCode($this->getPrimaryKey(), $this->zdb);
				
			} else {
				$this->_bin = array();
			}
			return $this->_bin;				
		}

		function getManytomanydata() {
			if (isset($this->_mtm )) {
				return $this->_mtm;
			} else if (!isset($this->_mtm) && !is_null($this->getPrimaryKey())){
				//we have no tags.. and possibly a primary .. so we should try and fault em
				// the get tags retuns an empty array.. if nothing is foudn..
				$this->_mtm = FTAORMCMSManyToManyWrapper::getAllManyToManyRecordsForParentCode($this->getPrimaryKey(), $this->zdb);
				
			} else {
				$this->_mtm = array();
			}
			return $this->_mtm;				
		}
		
		function getMultiplekeyvaluepairs() {
			if (isset($this->_mkvp )) {
				return $this->_mkvp;
			} else if (!isset($this->_mkvp) && !is_null($this->getPrimaryKey())){
				//we have no tags.. and possibly a primary .. so we should try and fault em
				// the get tags retuns an empty array.. if nothing is foudn..
				$this->_mkvp = FTAORMCMSMultipleKeyValuePair::getAllKeyValuePairsForDocumentCode($this->getPrimaryKey(), $this->zdb);
				
			} else {
				$this->_mkvp = array();
			}
			return $this->_mkvp;			
		}		

		// add helpers / defaults here for extra actions that happen at save/update time.. 		
		function save($newPrimaryKey = null){
			
			//we need to fault the cmscontent metadata.. as it is required.. 
			// and needs to be updated on save
			
			$this->cmscontentmetadata;
						
			$pk = $this->getPrimaryKey();
			
			if ((is_null($pk) || 0 == $pk) && is_null($newPrimaryKey)){
				$newPrimaryKey = static::getNewPrimaryKey($this->zdb);
			}
		
			return parent::save($newPrimaryKey);	
		}

		
		
// code for mapping to go ehre. 

		
		protected function _tableFieldsToTake(){			
			$f =  array_merge(array_keys($this->fieldMap), array($this->primaryKey, 'formid','documenttypecode'//,'cmscontentmetadata'
			));
			return $f;			
		}
		
		protected function _tableFieldsToValidate(){		
			$f =  array_merge(array_keys($this->fieldMap), array($this->primaryKey, 'formid','documenttypecode'//,'cmscontentmetadata'
			));
			return $f;			
		}
		
		//nothing for table fields to save, as this has a bit more complexity to it..
		protected function _tableFieldsToSave(){
			$f =  array_merge(array_keys($this->fieldMap), array($this->primaryKey, 'formid','documenttypecode'//,'cmscontentmetadata'
			));
			return $f;
		}
		
		protected function _tableRelationshipsToTake(){
			return array("cmscontentmetadata"=>FTAORM_RELATIONSHIP_ONE_TO_ONE, "tags"=> FTAORM_RELATIONSHIP_MANY_TO_MANY);
		}
		
		protected function _tableRelationshipsToValidate(){
			return array("cmscontentmetadata"=>FTAORM_RELATIONSHIP_ONE_TO_ONE, "tags"=> FTAORM_RELATIONSHIP_MANY_TO_MANY);			
		}
		
		protected function _tableRelationshipsToSave(){
			return array("cmscontentmetadata"=>FTAORM_RELATIONSHIP_ONE_TO_ONE, "tags"=> FTAORM_RELATIONSHIP_MANY_TO_MANY);				
		}
		
// saving /data insert ...

		
		protected function _dataForInsert(){
			//write data ..
			$data = array();
			$fieldsToSave = $this->_tableFieldsToSave();
			foreach ($fieldsToSave as $field	){
				if (isset($this->{ $field })) {
					$o = $this->getFieldValueForInsert($field);
					$data[ $this->mapNameToDatabaseField($field) ] = $o;

				}
			}	
			return $data;			
		}	

//mapping helpers

		function mapNameToDatabaseField($name){
			if (array_key_exists($name,$this->fieldMap)){
				return $this->fieldMap[$name];
			}
			return $name;
		}		
		
// Validation helpers.. 		
		function isFieldInvalid($field){
			$r = array_key_exists($field,$this->errors);
			return $r;	
		}
		
		//
		function getValidationMessageForField($field){

			if (array_key_exists($field ,$this->errors)){
				if (array_key_exists("additionalValidationError" ,$this->errors[ $field ] ) ){
					return $this->errors[ $field ]['additionalValidationError'];
				} else {
					switch($this->errors[ $field ][$field]){
						case FTAORM_FIELD_IS_REQUIRED:
						case FTAORM_RELATIONSHIP_IS_REQUIRED:
							return $field . " is required";
						break;
						
						case FTAORM_FIELD_IS_INVALID:
						case FTAORM_RELATIONSHIP_IS_INVALID:
						default:
							return $field . " is invalid";
						break;
					}
				}
			}
			return "";
		}
		
		
		
		
		//hack to work the the old pear sequence table
		//this assums that we already have a sequence table
		static function getNewPrimaryKey(Zend_Db_Adapter_Abstract $zdb){			
			$zdb->query('UPDATE ' . static::$TABLE_SEQUENCE_NAME .' SET id=LAST_INSERT_ID(id+1)');
			$id = $zdb->lastInsertId();
			return $id;
		}
		
		
		function load($id) {
			
			if (is_null($id))
				return false;
				
			$this->zdb->setFetchMode(Zend_Db::FETCH_ASSOC);
			$select = $this->zdb->select();
			
			//$select->from($this->tableName);
			
			if (count($this->fieldMap) > 0){
				$select = $select->from(array('m' => $this->tableName), $this->fieldMap );
			} else {
            	$select = $select->from(array('m' => $this->tableName) );
			}			
			
			
			$select->where($this->primaryKey .'=?', $id); 
			
			$statement = $select->query();
			$result = $statement->fetchAll();
			
			
			if (1 != count($result))	{
				//throw an error here.. WHEEEEE
				return null;
			}	
			
			//check for a valid object?? nah.. should be if its loaded..
			//
			
			$this->data = array();
			$this->setDefaults();
			$this->takeValuesFromArray($result[0]);

			// relationships will be lazy loaded
			$this->dataHasChanged = false;
			return true;			
		}
				
		
		
		
		public static function rowsToObjects($rows,$class,Zend_Db_Adapter_Abstract $zdb=null){
			$objects = array();
			if (is_array($rows)){
				foreach ($rows as $row){
					$oo = new $class($zdb);
					$oo->setDefaults();
					$oo->takeValuesFromArray($row);
					array_push($objects, $oo);
				}
			}
			return $objects;			
		}		
		

		static function getAll($zdb) {

			$myClass = get_called_class();
			
			$m = new $myClass($zdb);
			
			$zdb->setFetchMode(\Zend_Db::FETCH_ASSOC);
			
			$select = $zdb->select()// we may want to simplify this.. these should be a bit smarter..
            	->from(array('m' => $m->tableName), $m->fieldMap )
            	->from(array('md' => 'cmscontentmetadata'))
                ->where('md.documentcode = m.documentcode')
            	->where('formid = ?', $m->formid)                
            	->where('documenttypecode = ?', $m->documenttypecode)
            	->order('md.rank');
	        	//->where('categorycode = ?', $category->documentcode);
	        	
			$statement = $select->query();
			$result = $statement->fetchAll();
		
            return static::rowsToObjects($result,$myClass,$zdb);
		}
				
		static function getActiveWithId($id, $zdb){
			$o = static::getObjectWithId($id, $zdb);
			if ($o->cmscontentmetadata->isactive)
				return $o;
			else
				return null;
		}
		
	
	
	
        static function getAllActive($zdb) {

			$myClass = get_called_class();
            $date = date("Y-m-d H:i:s");
			
			$m = new $myClass($zdb);
			
			$zdb->setFetchMode(\Zend_Db::FETCH_ASSOC);
			
			$select = $zdb->select()// we may want to simplify this.. these should be a bit smarter..
            	->from(array('m' => $m->tableName), $m->fieldMap )
            	->from(array('md' => 'cmscontentmetadata'))
                ->where('md.documentcode = m.documentcode')
            	->where('formid = ?', $m->formid)                
            	->where('documenttypecode = ?', $m->documenttypecode)
            	->where('isactive = 1')
                // 2010-03-04 adding publish dates - JRM
                ->where('md.publishstartdate <= ?', $date) 
                ->where('md.publishenddate >= ?', $date)
            	->order('md.rank');
	        	//->where('categorycode = ?', $category->documentcode);
	        	
			$statement = $select->query();
			$result = $statement->fetchAll();
		
            return static::rowsToObjects($result,$myClass,$zdb);
		}
				

		

		public function getTags(){
					
			if (isset($this->_tags )) {
				return $this->_tags;
			} else if (!isset($this->_tags) && !is_null($this->getPrimaryKey())){
				//we have no tags.. and possibly a primary .. so we should try and fault em
				// the get tags retuns an empty array.. if nothing is foudn..
				$this->_tags = FTATag::getTagsForContent($this, $this->zdb);
			} else {
				$this->_tags = array();
			}
			return $this->_tags;
		}
		
		public function setTags($tags){
			// we need to first unset the current tags..
			// then set the new ones.. 
			// 
			$this->_tags = array();//clear out the current ones.

			//this 
			if (is_string($tags)){
				$this->_tags = FTATag::getTagsForString($tags, $this->zdb);	
			} else if (is_array($tags)){
				$this->_tags = FTATag::getTagsForArray($tags, $this->zdb);
			}
		}

		
		
	}	
	
	// DONT FUCKING ASK WHY THIS IS HERE.. 
	fta_registerModules(array(
			"FTAORM/FTAORMFullCMSContent",
			"FTAORM/FTAORMFullCmsContentMigrator",
			"FTAORM/FTAPageBuilderMigrator"
	));


	
	







